
/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package com.lxk.oms.order.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxk.event.helper.EventHelper;
import com.lxk.event.oms.OrderOptionLogEvent;
import com.lxk.event.oms.OrderPaySuccessEvent;
import com.lxk.event.oms.enums.OrderEnums;
import com.lxk.oms.log.domain.bo.OmsCommonOrderLogBo;
import com.lxk.oms.log.domain.vo.OmsCommonOrderLogVo;
import com.lxk.oms.log.service.IOmsCommonOrderLogService;
import com.lxk.oms.order.domain.OmsOrder;
import com.lxk.oms.order.domain.bo.OmsOrderBo;
import com.lxk.oms.order.domain.bo.OmsOrderItemBo;
import com.lxk.oms.order.domain.vo.OmsOrderVo;
import com.lxk.oms.order.mapper.OmsOrderMapper;
import com.lxk.oms.order.service.IOmsOrderItemService;
import com.lxk.oms.order.service.IOmsOrderService;
import com.lxk.service.core.Result;
import com.lxk.service.oms.api.OrderNotifyServiceApi;
import com.lxk.service.ums.api.UmsServiceApi;
import com.lxk.service.ums.response.UmsUserDto;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单Service业务层处理
 *
 * @author LXK-RY5
 * @date 2024-08-20
 */
@RequiredArgsConstructor
@Service
public class OmsOrderServiceImpl implements IOmsOrderService, OrderNotifyServiceApi {

    private final OmsOrderMapper baseMapper;
    private final IOmsOrderItemService orderItemService;
    private final UmsServiceApi umsServiceApi;
    private final IOmsCommonOrderLogService omsCommonOrderLogService;


    @Override
    public Boolean updateOrderWithInfo(Long orderId, OmsOrder update
    ) {
        int i = baseMapper.update(update, Wrappers.<OmsOrder>lambdaUpdate()
            .eq(OmsOrder::getId, orderId)
        );
        return i > 0;
    }

    @Override
    public Boolean updateBatchOrderStatusWithInfo(Long orderId, List<OrderEnums.OrderStatus> srcList, OrderEnums.OrderStatus dst,

                                                  OmsOrder update
    ) {
        update.setStatus(dst.getCode());
        int i = baseMapper.update(update, Wrappers.<OmsOrder>lambdaUpdate()
            .eq(OmsOrder::getId, orderId)
            .in(OmsOrder::getStatus, StreamUtils.toList(srcList, OrderEnums.OrderStatus::getCode))
        );
        return i > 0;
    }

    @Override
    public Boolean updateOrderStatusWithInfo(Long orderId, OrderEnums.OrderStatus src, OrderEnums.OrderStatus dst,
                                             OmsOrder update
    ) {
        update.setStatus(dst.getCode());
        int i = baseMapper.update(update, Wrappers.<OmsOrder>lambdaUpdate()
            .eq(OmsOrder::getId, orderId)
            .eq(OmsOrder::getStatus, src.getCode())
        );
        return i > 0;
    }

    @Override
    public Boolean updateOrderStatus(Long orderId, OrderEnums.OrderStatus src, OrderEnums.OrderStatus dst) {
        OmsOrder update = new OmsOrder();
        update.setStatus(dst.getCode());
        int i = baseMapper.update(update, Wrappers.<OmsOrder>lambdaUpdate()
            .eq(OmsOrder::getId, orderId)
            .eq(OmsOrder::getStatus, src.getCode())
        );
        return i > 0;
    }

    @Override
    public Boolean updateOrderPostStatus(Long orderId, OrderEnums.PostStatus src, OrderEnums.PostStatus dst) {
        OmsOrder update = new OmsOrder();
        update.setPostStatus(dst.getCode());
        int i = baseMapper.update(update, Wrappers.<OmsOrder>lambdaUpdate()
            .eq(OmsOrder::getId, orderId)
            .eq(OmsOrder::getPostStatus, src.getCode())
        );
        return i > 0;
    }

    @Override
    public Boolean paySuccess(String orderNo, Long userId, String paySn, String payType) {
        OmsOrderVo omsOrderVo = queryByOrderSn(orderNo, userId);
        return paySuccess(omsOrderVo, paySn, payType);
    }

    @Override
    public Boolean paySuccess(OmsOrderVo omsOrderVo, String paySn, String payType) {
        Long id = omsOrderVo.getId();
        Date now = new Date();
        OmsOrder update = new OmsOrder();
        update.setPayTime(now);
        update.setPayType(payType);
        update.setPayOrderSn(paySn);
        update.setPayStatus(OrderEnums.PayStatus.YES.getCode());
        update.setStatus(OrderEnums.OrderStatus.SEND_300.getCode());
        int row = baseMapper.update(update, Wrappers.<OmsOrder>lambdaUpdate()
            .eq(OmsOrder::getId, id)
            .eq(OmsOrder::getStatus, OrderEnums.OrderStatus.PAYING_100.getCode())
        );
        return row > 0;
    }

    /**
     * 支付成功,支持内部合单支付
     *
     * @param outTradeNo  支付订单号
     * @param paySn
     * @param attach  补充参数
     * @return
     */
    @Override
    public Boolean notifySuccess(String outTradeNo, String paySn, String attach) {
        List<OmsOrderVo> orderList = queryListByOutTradeNo(outTradeNo);
        if (CollUtil.isEmpty(orderList) && StringUtils.isNotBlank(attach)) {
            orderList = queryListByOrderSn(attach);
        }
        if (CollUtil.isEmpty(orderList)) {
            throw new ServiceException("订单信息不存在");
        }
        orderList.forEach(order -> {
            if (OrderEnums.OrderStatus.PAYING_100.getCode().equals(order.getStatus())) {
                Boolean success = paySuccess(order, paySn, order.getPayType());
                if (!success) {
                    throw new ServiceException("订单支付异常");
                }
                OrderOptionLogEvent createEvent = new OrderOptionLogEvent();
                UmsUserDto umsUserDto = umsServiceApi.queryById(order.getUserId()).getData();
                Long merId = order.getMerId();
                Long userId = umsUserDto.getUserId();
                String nickName = umsUserDto.getNickName();
                createEvent.setOrderSn(order.getOrderNo());
                createEvent.setUserId(userId);
                createEvent.setMerId(merId);
                createEvent.setOrderLogEnums(OrderOptionLogEvent.OrderLogEnums.ORDER);
                createEvent.setUserType(umsUserDto.getUserType());
                createEvent.setContent(
                    OrderOptionLogEvent.OrderContentFormatEnums.PAY_SUCCESS_ORDER.formatContent(nickName,
                        order.getOrderNo(),
                        OrderEnums.PayType.getByCode(order.getPayType()).getName())
                );
                EventHelper.publishEvent(createEvent);

                // 支付成功
                OrderPaySuccessEvent successEvent = new OrderPaySuccessEvent();
                successEvent.setActPayPrice(order.getActPayPrice());
                successEvent.setUserId(umsUserDto.getUserId());
                successEvent.setTenantId(order.getTenantId());
                successEvent.setOrderType(order.getOrderType());
                successEvent.setOrderNo(order.getOrderNo());
                successEvent.setOrderId(order.getId());
                successEvent.setOrderName(order.getOrderName());
                EventHelper.publishEvent(createEvent);
            }
        });

        return true;
    }

    /**
     * 查询订单
     *
     * @param orderNo 订单编号
     * @return 订单
     */
    @Override
    public OmsOrderVo queryByOrderSn(String orderNo, Long userId) {
        return baseMapper.selectVoOne(Wrappers.<OmsOrder>lambdaQuery().eq(OmsOrder::getOrderNo, orderNo).eq(OmsOrder::getUserId, userId));
    }

    /**
     * 批量查询订单
     *
     * @param orderNo 订单编号
     * @return 订单
     */
    @Override
    public List<OmsOrderVo> queryByOrderSnList(List<String> orderNoList, Long userId) {
        return baseMapper.selectVoList(Wrappers.<OmsOrder>lambdaQuery().in(OmsOrder::getOrderNo, orderNoList).eq(OmsOrder::getUserId, userId));
    }

    @Override
    public OmsOrderVo queryByOrderSn(String orderNo) {
        return baseMapper.selectVoOne(Wrappers.<OmsOrder>lambdaQuery().eq(OmsOrder::getOrderNo, orderNo));
    }

    @Override
    public List<OmsOrderVo> queryListByOrderSn(String orderNo) {
        return baseMapper.selectVoList(Wrappers.<OmsOrder>lambdaQuery().eq(OmsOrder::getOrderNo, orderNo));
    }

    @Override
    public OmsOrderVo queryByPayOrderSn(String payOrderNo) {
        return baseMapper.selectVoOne(Wrappers.<OmsOrder>lambdaQuery().eq(OmsOrder::getPayOrderSn, payOrderNo));
    }

    @Override
    public OmsOrderVo queryByOutTradeNo(String outTradeNo) {
        return baseMapper.selectVoOne(Wrappers.<OmsOrder>lambdaQuery().eq(OmsOrder::getOutTradeNo, outTradeNo));
    }

    @Override
    public List<OmsOrderVo> queryListByOutTradeNo(String outTradeNo) {
        return baseMapper.selectVoList(Wrappers.<OmsOrder>lambdaQuery().eq(OmsOrder::getOutTradeNo, outTradeNo));
    }


    /**
     * 查询IdList订单Map
     */
    @Override
    public Map<Long, OmsOrderVo> queryMapByIdList(List<Long> idList) {
        return this.queryByIdList(idList).stream().collect(Collectors.toMap(OmsOrderVo::getId, v -> v));
    }

    /**
     * 查询订单Map
     */
    @Override
    public Map<Long, OmsOrderVo> queryMap(OmsOrderBo bo) {
        return this.queryList(bo).stream().collect(Collectors.toMap(OmsOrderVo::getId, v -> v));
    }

    /**
     * 查询订单IdList
     */
    @Override
    public List<OmsOrderVo> queryByIdList(List<Long> idList) {
        if (CollUtil.isEmpty(idList)) {
            return CollUtil.newArrayList();
        }
        LambdaQueryWrapper<OmsOrder> lqw = Wrappers.lambdaQuery();
        lqw.in(OmsOrder::getId, idList);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询订单
     *
     * @param id 主键
     * @return 订单
     */
    @Override
    public OmsOrderVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 订单详情
     *
     * @param id 主键
     * @return 订单
     */
    @Override
    public OmsOrderVo detail(Long id) {
        OmsOrderVo orderVo = this.queryById(id);
        if (orderVo == null) {
            throw new ServiceException("订单信息不存在");
        }
        Result<UmsUserDto> result = umsServiceApi.queryById(orderVo.getUserId());
        if (result.getData() != null) {
            orderVo.setNickName(result.getData().getNickName());
        }
        OmsOrderItemBo query = new OmsOrderItemBo();
        query.setOrderId(id);
        orderVo.setOrderItemVoList(orderItemService.queryList(query));
        // 增加日志
        OmsCommonOrderLogBo logBo = new OmsCommonOrderLogBo();
        logBo.setOmsSn(orderVo.getOrderNo());
        List<OmsCommonOrderLogVo> logVoList = omsCommonOrderLogService.queryList(logBo);
        orderVo.setLogVoList(logVoList);
        return orderVo;
    }

    /**
     * 分页查询订单列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 订单分页列表
     */
    @Override
    public TableDataInfo<OmsOrderVo> queryPageList(OmsOrderBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<OmsOrder> lqw = buildQueryWrapper(bo);
        Page<OmsOrderVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (CollUtil.isEmpty(result.getRecords())) {
            return TableDataInfo.build(result);
        }
        List<Long> userIdList = result.getRecords().stream().map(OmsOrderVo::getUserId).distinct().collect(Collectors.toList());
        if (CollUtil.isNotEmpty(userIdList)) {
            Result<List<UmsUserDto>> res = umsServiceApi.queryByIdList(userIdList);
            Map<Long, UmsUserDto> map = res.getData().stream().collect(Collectors.toMap(UmsUserDto::getUserId, v -> v));
            result.getRecords().forEach(r -> {
                r.setNickName(map.get(r.getUserId()).getNickName());
            });
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的订单列表
     *
     * @param bo 查询条件
     * @return 订单列表
     */
    @Override
    public List<OmsOrderVo> queryList(OmsOrderBo bo) {
        LambdaQueryWrapper<OmsOrder> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询支付中第三方订单列表
     *
     * @return 订单列表
     */
    @Override
    public Page<OmsOrderVo> queryThirdPayingOrderPageList(PageQuery pageQuery) {
        LambdaQueryWrapper<OmsOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(OmsOrder::getStatus, OrderEnums.OrderStatus.PAYING_100.getCode());
        lqw.in(OmsOrder::getPayType, OrderEnums.PayType.THIRD_PAY);
        Page<OmsOrderVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return result;
    }

    private LambdaQueryWrapper<OmsOrder> buildQueryWrapper(OmsOrderBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<OmsOrder> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(OmsOrder::getId);
        lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
            OmsOrder::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
        lqw.between(params.get("beginUpdateTime") != null && params.get("endUpdateTime") != null,
            OmsOrder::getUpdateTime, params.get("beginUpdateTime"), params.get("endUpdateTime"));
        lqw.eq(bo.getMerId() != null, OmsOrder::getMerId, bo.getMerId());
        lqw.eq(StringUtils.isNotBlank(bo.getOrderNo()), OmsOrder::getOrderNo, bo.getOrderNo());
        lqw.eq(bo.getOrderType() != null, OmsOrder::getOrderType, bo.getOrderType());
        lqw.eq(bo.getUserId() != null, OmsOrder::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getUserIp()), OmsOrder::getUserIp, bo.getUserIp());
        lqw.eq(StringUtils.isNotBlank(bo.getUserRemark()), OmsOrder::getUserRemark, bo.getUserRemark());
        lqw.eq(StringUtils.isNotBlank(bo.getMerRemark()), OmsOrder::getMerRemark, bo.getMerRemark());
        lqw.eq(StringUtils.isNotBlank(bo.getPlatformRemark()), OmsOrder::getPlatformRemark, bo.getPlatformRemark());
        lqw.eq(bo.getStatus() != null, OmsOrder::getStatus, bo.getStatus());
        lqw.eq(bo.getTotalPrice() != null, OmsOrder::getTotalPrice, bo.getTotalPrice());
        lqw.eq(bo.getDiscountPrice() != null, OmsOrder::getDiscountPrice, bo.getDiscountPrice());
        lqw.eq(bo.getPayPrice() != null, OmsOrder::getPayPrice, bo.getPayPrice());
        lqw.eq(bo.getActPayPrice() != null, OmsOrder::getActPayPrice, bo.getActPayPrice());
        lqw.eq(bo.getPayStatus() != null, OmsOrder::getPayStatus, bo.getPayStatus());
        lqw.between(params.get("beginPayTime") != null && params.get("endPayTime") != null,
            OmsOrder::getPayTime, params.get("beginPayTime"), params.get("endPayTime"));
        lqw.eq(StringUtils.isNotBlank(bo.getPayOrderSn()), OmsOrder::getPayOrderSn, bo.getPayOrderSn());
        lqw.eq(StringUtils.isNotBlank(bo.getPayType()), OmsOrder::getPayType, bo.getPayType());
        lqw.between(params.get("beginFinishTime") != null && params.get("endFinishTime") != null,
            OmsOrder::getFinishTime, params.get("beginFinishTime"), params.get("endFinishTime"));
        lqw.eq(StringUtils.isNotBlank(bo.getCancelReason()), OmsOrder::getCancelReason, bo.getCancelReason());
        lqw.between(params.get("beginCancelTime") != null && params.get("endCancelTime") != null,
            OmsOrder::getCancelTime, params.get("beginCancelTime"), params.get("endCancelTime"));
        lqw.between(params.get("beginDeliveryTime") != null && params.get("endDeliveryTime") != null,
            OmsOrder::getDeliveryTime, params.get("beginDeliveryTime"), params.get("endDeliveryTime"));
        lqw.between(params.get("beginReceiveTime") != null && params.get("endReceiveTime") != null,
            OmsOrder::getReceiveTime, params.get("beginReceiveTime"), params.get("endReceiveTime"));
        lqw.like(StringUtils.isNotBlank(bo.getReceiverName()), OmsOrder::getReceiverName, bo.getReceiverName());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiverMobile()), OmsOrder::getReceiverMobile, bo.getReceiverMobile());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiverDetailAddress()), OmsOrder::getReceiverDetailAddress, bo.getReceiverDetailAddress());
        lqw.eq(bo.getOrderProvinceId() != null, OmsOrder::getOrderProvinceId, bo.getOrderProvinceId());
        lqw.like(StringUtils.isNotBlank(bo.getOrderProvinceName()), OmsOrder::getOrderProvinceName, bo.getOrderProvinceName());
        lqw.eq(bo.getOrderCityId() != null, OmsOrder::getOrderCityId, bo.getOrderCityId());
        lqw.like(StringUtils.isNotBlank(bo.getOrderCityName()), OmsOrder::getOrderCityName, bo.getOrderCityName());
        lqw.eq(bo.getOrderDistrictId() != null, OmsOrder::getOrderDistrictId, bo.getOrderDistrictId());
        lqw.like(StringUtils.isNotBlank(bo.getOrderDistrictName()), OmsOrder::getOrderDistrictName, bo.getOrderDistrictName());
        lqw.eq(bo.getUserDelFlag() != null, OmsOrder::getUserDelFlag, bo.getUserDelFlag());
        lqw.eq(bo.getMerDelFlag() != null, OmsOrder::getMerDelFlag, bo.getMerDelFlag());
        lqw.between(params.get("beginDivideStartTime") != null && params.get("endDivideStartTime") != null,
            OmsOrder::getDivideStartTime, params.get("beginDivideStartTime"), params.get("endDivideStartTime"));
        lqw.eq(bo.getDivideStatus() != null, OmsOrder::getDivideStatus, bo.getDivideStatus());
        lqw.between(params.get("beginDivideCompleteTime") != null && params.get("endDivideCompleteTime") != null,
            OmsOrder::getDivideCompleteTime, params.get("beginDivideCompleteTime"), params.get("endDivideCompleteTime"));
        lqw.eq(bo.getRefundAmount() != null, OmsOrder::getRefundAmount, bo.getRefundAmount());
        lqw.eq(bo.getRefundStatus() != null, OmsOrder::getRefundStatus, bo.getRefundStatus());
        lqw.eq(bo.getPostStatus() != null, OmsOrder::getPostStatus, bo.getPostStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getShipperCode()), OmsOrder::getShipperCode, bo.getShipperCode());
        lqw.eq(StringUtils.isNotBlank(bo.getDeliverySn()), OmsOrder::getDeliverySn, bo.getDeliverySn());
        lqw.like(StringUtils.isNotBlank(bo.getDeliveryName()), OmsOrder::getDeliveryName, bo.getDeliveryName());
        lqw.eq(bo.getDeliveryType() != null, OmsOrder::getDeliveryType, bo.getDeliveryType());
        return lqw;
    }

    /**
     * 新增订单
     *
     * @param bo 订单
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(OmsOrderBo bo) {
        OmsOrder add = MapstructUtils.convert(bo, OmsOrder.class);
        validEntityBeforeSave(add);
        add.setCreateOrderTime(new Date());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改订单
     *
     * @param bo 订单
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(OmsOrderBo bo) {
        OmsOrder update = MapstructUtils.convert(bo, OmsOrder.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OmsOrder entity) {
    }

    /**
     * 校验并批量删除订单信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public Boolean setPayType(Long id, String payType, String outTradeNo) {
        OmsOrder update = new OmsOrder();
        update.setId(id);
        update.setPayType(payType);
        update.setOutTradeNo(outTradeNo);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public Boolean setUnPay(Long id) {
        OmsOrder update = new OmsOrder();
        update.setStatus(OrderEnums.OrderStatus.CREATE_0.getCode());
        int row = baseMapper.update(update, Wrappers.<OmsOrder>lambdaUpdate()
            .eq(OmsOrder::getId, id)
            .eq(OmsOrder::getStatus, OrderEnums.OrderStatus.PAYING_100.getCode())
        );
        return row > 0;
    }

    @Override
    public Boolean setPayTimeOut(Long id) {
        OmsOrder update = new OmsOrder();
        update.setStatus(OrderEnums.OrderStatus.CANCEL_501.getCode());
        int row = baseMapper.update(update, Wrappers.<OmsOrder>lambdaUpdate()
            .eq(OmsOrder::getId, id)
            .eq(OmsOrder::getStatus, OrderEnums.OrderStatus.PAYING_100.getCode())
        );
        return row > 0;
    }
}
